<template>
	<div class="container">
		<div
			:class="`tag ${deletingIdx === index ? 'deleting' : ''}`"
			v-for="(item, index) in list"
			:key="item.id"
		>
			<div>{{ item.tag }}</div>
			<span @click="deleteTag(item.id, index)">×</span>
		</div>

		<div class="tag add" @click="addTab">
			<!-- 没修改中 -->
			<template v-if="!isInput">
				<span>＋</span>
				<div>新增标签</div>
			</template>
			<!-- 修改中 -->
			<template v-else>
				<input
					v-focus
					type="text"
					v-model.trim="editingValue"
					@blur="blur"
					@keyup.enter="blur()"
				/>
			</template>
		</div>
	</div>
</template>
<script>
let idCounter = 4;
export default {
	// 自定义focus指令
	directives: {
		focus: {
			inserted(el) {
				// el表示指令所绑定的函数
				el.focus();
			},
		},
	},
	data() {
		return {
			list: [
				{
					id: 1,
					tag: "标签一",
				},
				{
					id: 2,
					tag: "标签二",
				},
				{
					id: 3,
					tag: "标签三",
				},
			],
			deletingIdx: -1,
			editingValue: "",
			isInput: false,
		};
	},
	methods: {
		addTab() {
			this.isInput = true;
		},
		deleteTag(id, index) {
			this.deletingIdx = index;
			setTimeout(() => {
				// 500ms后删除数据
				this.list = this.list.filter((item) => item.id !== id);
				// 置回
				this.deletingIdx = -1;
			}, 500);
		},
		blur() {
			this.isInput = false;
			const res = {
				id: idCounter++,
				tag: this.editingValue,
			};
			this.editingValue && this.list.push(res);
			this.editingValue = "";
			this.deletingIdx = this.list.length - 1;
			setTimeout(() => {
				// 置回
				this.deletingIdx = -1;
			}, 500);
		},
	},
};
</script>

<style scoped>
.tag {
	width: 100px;
	height: 30px;
	border-radius: 4px;
	border: 1px solid red;
	line-height: 30px;
	padding: 0px 12px;
	display: flex;
	justify-content: space-between;
	margin-right: 50px;
	transition: transform 0.5s ease;
	transform: rotateY(0deg);
}
.tag.deleting {
	transform: rotateY(90deg);
}
.container {
	display: flex;
}
input {
	width: 100px;
	outline: none;
	border: none;
}
</style>